package com.shopping_back.controller;

import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.UserInfoDTO;
import com.shopping_back.pojo.entity.UserProfile;
import com.shopping_back.service.IUserProfileService;
import com.shopping_back.service.MemberService;
import com.shopping_back.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

/**
 * <p>
 * 用户档案表 前端控制器
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@CrossOrigin
@RestController
@RequestMapping("api/profile")
public class UserProfileController {
    @Autowired
    private IUserProfileService userProfileService;

    @Autowired
    private  JwtUtils jwtUtils;

    @Autowired
    private MemberService memberService;


    @GetMapping("/wallet")
    public Result getWallet(@RequestParam int id) {
        Integer wallet = userProfileService.getById(id).getWallet();
        return Result.success(wallet);
    }
    /**
     * 查询用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result getUserInfo(@RequestParam Long userId) {
        return Result.success(userProfileService.getUserInfo(userId));
    }

    /**
     * 更新用户信息
     * @param userInfoDTO 用户信息DTO
     */
    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody UserInfoDTO userInfoDTO) {
        System.out.println(userInfoDTO);
        userProfileService.updateUserInfo(userInfoDTO);
        return Result.success();
    }
    @PostMapping("/getMember")
    public Result getMember(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        // 1. 从Token获取用户ID
        Long userId = jwtUtils.getCurrentUserId(request);
        if (userId == null) {
            return Result.error("401", "无效的登录状态");
        }

        // 2. 查询数据库（使用图片中的membership_level字段）
        UserProfile profile = userProfileService.getByUserId(userId);
        if (profile == null) {
            return Result.error("404", "会员信息不存在");
        }

        // 3. 返回数据（字段名与前端匹配）
        return Result.success(profile);
    }

    @GetMapping("/memValidity")
    public Result getMemberValidity(HttpServletRequest request) {
        try {
            Map<String, String> result = memberService.getMemberValidity(request);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("500", "获取会员信息失败");
        }
    }

    @PostMapping("/downgrade")
    public Result triggerDowngrade(HttpServletRequest request) {
        Long userId = jwtUtils.getCurrentUserId(request);

        if (memberService.executeAutoDowngrade(userId)) {
            return Result.success("会员已降级为普通用户");
        }
        return Result.success("当前会员状态正常");
    }

    // 获取可升级选项
    @GetMapping("/upgrade-options")
    public Result getUpgradeOptions(HttpServletRequest request) {
        Long userId = jwtUtils.getCurrentUserId(request);
        return Result.success(memberService.getAvailableLevels(userId));
    }

    // 执行升级（支付成功后调用）
    @PostMapping("/upgrade")
    public Result upgrade(
            @RequestParam String targetLevel,
            @RequestParam String months,
            HttpServletRequest request) {
        try {
            Integer targetLevelInt = Integer.parseInt(targetLevel);
            Integer monthsInt = Integer.parseInt(months);
            Long userId = jwtUtils.getCurrentUserId(request);
            System.out.println("接收到的 targetLevel 参数值：" + targetLevelInt);
            System.out.println("接收到的 targetLevel 参数类型：" + targetLevelInt.getClass());
            return memberService.upgradeMember(userId, targetLevelInt, monthsInt);
        } catch (NumberFormatException e) {
            return Result.error("参数类型错误，targetLevel 或 months 需为数字");
        }
    }

    // 执行续费（支付成功后调用）
    @PostMapping("/renew")
    public Result renew(
            @RequestParam Long orderId,
            @RequestParam Integer months) {
        return memberService.renewMember(orderId, months);
    }

    @PostMapping("/exchange-points")
    public UserProfile exchangePoints(
            @RequestParam Long userId,
            @RequestParam Integer points,
            @RequestParam Integer wallet) {
        return userProfileService.exchangePoints(userId, points, wallet);
    }

    @PostMapping("/addPoints")
    public Result addPoints(@RequestBody Map<String, Object> requestMap, HttpServletRequest request) {
        // 1. 参数校验
        if (!requestMap.containsKey("points")) {
            return Result.error("400", "缺少必要参数");
        }

        try {
            // 2. 参数解析
            int points = (Integer) requestMap.get("points");
            String source = (String) requestMap.get("source");
            String orderSn = (String) requestMap.get("orderSn");

            // 4. 执行积分增加
            Long userId = jwtUtils.getCurrentUserId(request);
            int updated = userProfileService.addPoints(userId, points);

            if (updated > 0) {
                return Result.success("积分添加成功");
            } else {
                return Result.error("积分添加失败");
            }
        } catch (ClassCastException e) {
            return Result.error("400", "参数类型错误");
        } catch (Exception e) {
            return Result.error("500", "系统繁忙");
        }
    }


}
